import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/common/permission/permission_manager.dart';
import 'package:tracker/pages/home/fence/model/fence_list_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/num_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

/// 创建围栏 页面
class CreateFencePage extends ConsumerStatefulWidget {
  CreateFencePage({this.fenceData, super.key});

  FenceData? fenceData;

  @override
  ConsumerState<CreateFencePage> createState() => _CreateFencePageState();
}

class _CreateFencePageState extends ConsumerState<CreateFencePage> {
  BMFMapOptions mapOptions = BMFMapOptions(
      center: BMFCoordinate(39.917215, 116.380341),
      zoomLevel: 18,
      mapPadding: BMFEdgeInsets(left: 30, top: 0, right: 30, bottom: 0));

  BMFMapController? myMapController;
  BMFCircle? circle;
  // 圆点
  BMFCircle? circleCenter;

  /// 围栏半径，最小100米，最大5000米
  double radius = 100;

  /// 围栏名称
  String fenceName = '';

  /// 围栏名称输入框
  final TextEditingController _fenceNameController = TextEditingController();

  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();

  onBMFMapCreated(BMFMapController controller) {
    myMapController = controller;
    myMapController?.setMapDidLoadCallback(callback: () {
      XLogger.debug('地图加载完成');
      if (widget.fenceData == null) {
        _startLocation();
      } else {
        fenceName = widget.fenceData!.name ?? '';
        radius = widget.fenceData!.radius ?? 100;
        setState(() {});
        myMapController?.setCenterCoordinate(
            BMFCoordinate(widget.fenceData!.latitude!, widget.fenceData!.longitude!), true);
        _drawCircle(widget.fenceData!.latitude!, widget.fenceData!.longitude!, widget.fenceData!.radius!);
        _setZoomLevelByRadius();
      }
    });
    myMapController?.updateMapOptions(BMFMapOptions(
      logoPosition: BMFLogoPosition.LeftTop,
      showZoomControl: false,
    ));
    myMapController?.setMapRegionDidChangeCallback(callback: (BMFMapStatus mapStatus) {
      XLogger.debug('地图区域发生变化: ${mapStatus.targetGeoPt?.latitude}, ${mapStatus.targetGeoPt?.longitude}');
      if (circle != null) {
        _drawCircle(mapStatus.targetGeoPt!.latitude, mapStatus.targetGeoPt!.longitude, radius);
      }
    });
  }

  Widget _buildBottomView() {
    final sliderLabel = NumUtils.formatNum(radius, format: '#');
    return Positioned(
      bottom: 20,
      left: 20,
      right: 20,
      child: Column(
        children: [
          Container(
            child: Slider(
              value: radius,
              min: 100,
              max: 5000,
              divisions: 49,
              label: '${sliderLabel}米',
              onChanged: (value) {
                // value 四舍五入，取整数
                value = value.roundToDouble();
                setState(() {
                  radius = value;
                });
                // 改变地图缩放级别
                _setZoomLevelByRadius();
              },
            ),
          ),
          Container(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {
                if (widget.fenceData != null) {
                  _fenceNameController.text = widget.fenceData!.name ?? '';
                }
                // 弹窗输入围栏名称
                showDialog(
                    context: context,
                    builder: (context) {
                      return AlertDialog(
                        title: const Text('请输入围栏名称'),
                        content: TextField(
                          controller: _fenceNameController,
                          onChanged: (value) {
                            fenceName = value;
                          },
                        ),
                        actions: [
                          TextButton(
                            onPressed: () {
                              context.pop();
                            },
                            child: const Text('取消'),
                          ),
                          TextButton(
                            onPressed: () {
                              if (fenceName.isEmpty) {
                                ToastUtils.showToast('请输入围栏名称');
                                return;
                              }
                              context.pop();
                              if (widget.fenceData != null) {
                                // 修改围栏
                                _updateFence();
                              } else {
                                // 新建围栏
                                _createFence();
                              }
                            },
                            child: const Text('确定'),
                          ),
                        ],
                      );
                    });
              },
              style: ElevatedButton.styleFrom(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                backgroundColor: AppTheme.themeConfig.primaryColor,
              ),
              child: const Text(
                '保存',
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 新建围栏
  _createFence() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'name': fenceName,
      'radius': radius,
      'longitude': circle?.center.longitude,
      'latitude': circle?.center.latitude,
      'coordinateType': 2
    };
    final res = await post<BaseResp, BaseResp>('/electronic-fence/add', data: postData, decodeType: BaseResp());
    res.when(success: (BaseResp resp) {
      if (resp.code == 200) {
        ToastUtils.showToast('创建成功');
        context.pop(true);
      } else {
        ToastUtils.showToast(resp.msg ?? '创建失败');
      }
    }, failure: (String msg, int code) {
      ToastUtils.showToast('创建失败');
    });
  }

  /// 修改围栏
  _updateFence() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final postData = {
      'id': widget.fenceData?.id,
      'imei': deviceInfo.imei,
      'name': fenceName,
      'radius': radius,
      'longitude': circle?.center.longitude,
      'latitude': circle?.center.latitude,
      'coordinateType': 2
    };
    final res = await post<BaseResp, BaseResp>('/electronic-fence/update', data: postData, decodeType: BaseResp());
    res.when(success: (BaseResp resp) {
      if (resp.code == 200) {
        ToastUtils.showToast('修改成功');
        context.pop(true);
      } else {
        ToastUtils.showToast(resp.msg ?? '修改失败');
      }
    }, failure: (String msg, int code) {
      ToastUtils.showToast('修改失败');
    });
  }

  BaiduLocationAndroidOption initAndroidOptions() {
    BaiduLocationAndroidOption options = BaiduLocationAndroidOption(
        // 定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        locationMode: BMFLocationMode.hightAccuracy,
        // 是否需要返回地址信息
        isNeedAddress: true,
        // 是否需要返回海拔高度信息
        isNeedAltitude: true,
        // 是否需要返回周边poi信息
        isNeedLocationPoiList: false,
        // 是否需要返回新版本rgc信息
        isNeedNewVersionRgc: false,
        // 是否需要返回位置描述信息
        isNeedLocationDescribe: false,
        // 是否使用gps
        openGps: true,
        // 可选，设置场景定位参数，包括签到场景、运动场景、出行场景
        locationPurpose: BMFLocationPurpose.sport,
        // 坐标系
        coordType: BMFLocationCoordType.gcj02,
        // 设置发起定位请求的间隔，int类型，单位ms
        // 如果设置为0，则代表单次定位，即仅定位一次，默认为0
        scanspan: 500);
    return options;
  }

  BaiduLocationIOSOption initIOSOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
      // 坐标系
      coordType: BMFLocationCoordType.gcj02,
      // 位置获取超时时间
      locationTimeout: 10,
      // 获取地址信息超时时间
      reGeocodeTimeout: 10,
      // 应用位置类型 默认为automotiveNavigation
      activityType: BMFActivityType.automotiveNavigation,
      // 设置预期精度参数 默认为best
      desiredAccuracy: BMFDesiredAccuracy.best,
      // 是否需要最新版本rgc数据
      isNeedNewVersionRgc: true,
      // 指定定位是否会被系统自动暂停
      pausesLocationUpdatesAutomatically: false,
      // 指定是否允许后台定位,
      // 允许的话是可以进行后台定位的，但需要项目配置允许后台定位，否则会报错，具体参考开发文档
      allowsBackgroundLocationUpdates: true,
      // 设定定位的最小更新距离
      distanceFilter: 10,
    );
    return options;
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {});
    super.initState();
    PermissionManager.requestLocationPermissions(context);
  }

  _startLocation() async {
    if (Platform.isIOS) {
      //接受定位回调
      _myLocPlugin.singleLocationCallback(callback: (BaiduLocation result) {
        //result为定位结果
        XLogger.debug('开始单次定位：${result.longitude}, ${result.latitude}, ${result.radius}');
        myMapController?.setCenterCoordinate(BMFCoordinate(result.latitude!, result.longitude!), true);
        _drawCircle(result.latitude!, result.longitude!, radius);
        XLogger.debug('定位结束');
      });
    } else if (Platform.isAndroid) {
      //接受定位回调
      _myLocPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
        //result为定位结果
        XLogger.debug('定位结果: ${result.longitude}, ${result.latitude}, ${result.radius}');
        if (circle == null) {
          myMapController?.setCenterCoordinate(BMFCoordinate(result.latitude!, result.longitude!), true);
          _drawCircle(result.latitude!, result.longitude!, radius);
        }
      });
    }
    Map iosMap = initIOSOptions().getMap();
    Map androidMap = initAndroidOptions().getMap();

    await _myLocPlugin.prepareLoc(androidMap, iosMap);
    if (Platform.isIOS) {
      await _myLocPlugin.singleLocation({'isReGeocode': true, 'isNetworkState': true});
    } else if (Platform.isAndroid) {
      await _myLocPlugin.startLocation();
    }
  }

  /// 画一个圆形围栏
  _drawCircle(double latitude, double longitude, double? radius) {
    if (radius == null || radius <= 0) {
      radius = 100;
    }
    XLogger.debug('画一个圆形围栏: $latitude, $longitude, $radius');
    if (circle == null) {
      circle = BMFCircle(
        center: BMFCoordinate(latitude, longitude),
        radius: radius,
        width: 1,
        strokeColor: ColorUtils.hexToColor('#165DFF'),
        fillColor: ColorUtils.hexToColor('#50165DFF'),
        lineDashType: BMFLineDashType.LineDashTypeNone,
        zIndex: 10,
      );
      myMapController?.addCircle(circle!);
      circleCenter = BMFCircle(
        center: BMFCoordinate(latitude, longitude),
        radius: radius * 0.1,
        width: 1,
        strokeColor: ColorUtils.hexToColor('#165DFF'),
        fillColor: ColorUtils.hexToColor('#165DFF'),
        lineDashType: BMFLineDashType.LineDashTypeNone,
        zIndex: 20,
      );
      myMapController?.addCircle(circleCenter!);
    } else {
      circle?.updateCenter(BMFCoordinate(latitude, longitude));
      circle?.updateRadius(radius);
      circleCenter?.updateCenter(BMFCoordinate(latitude, longitude));
      circleCenter?.updateRadius(radius * 0.1);
    }
  }

  /// radius与地图缩放级别的比例
  void _setZoomLevelByRadius() {
    double zoomLevel = 18;
    if (radius <= 100) {
      zoomLevel = 18;
    } else if (radius <= 200) {
      zoomLevel = 17;
    } else if (radius <= 500) {
      zoomLevel = 16;
    } else if (radius <= 1000) {
      zoomLevel = 15;
    } else if (radius <= 2000) {
      zoomLevel = 14;
    } else if (radius <= 5000) {
      zoomLevel = 13;
    } else {
      zoomLevel = 12;
    }
    if (Platform.isAndroid) {
      myMapController?.setZoomTo(zoomLevel);
    } else {
      // iOS缩放地图
      BMFMapOptions mapOptions = BMFMapOptions(
        zoomLevel: zoomLevel.toInt(),
      );
      myMapController?.updateMapOptions(mapOptions);
    }
  }

  @override
  void dispose() {
    _myLocPlugin.stopLocation();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final title = widget.fenceData == null ? '创建围栏' : '编辑围栏';
    return Scaffold(
      appBar: AppBar(
        title: Text(
          title,
          style: const TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: Stack(
        children: [
          BMFMapWidget(
            onBMFMapCreated: (controller) {
              onBMFMapCreated(controller);
            },
            mapOptions: mapOptions,
          ),
          _buildBottomView(),
        ],
      ),
    );
  }
}
